#usr/bin/bash
create_lv () {
  local name=$1
  local size=$2
  local fs=$3
  lvcreate -L$size -n$name lvm_volume_group
  mkfs -t $fs /dev/lvm_volume_group/$name
}

replace_mnt () {
  local part=$1
  local name=$2
  local uuid=`blkid $part | grep 'UUID=".*"' | sed -E 's/.*UUID=\"([^\"]*).*/\1/'`
  local label=`blkid $part | grep 'LABEL=".*"' | sed -E 's/.*LABEL=\"([^\"]*).*/\1/'`
  local escaped_part=`echo $part | sed 's/\//%\//g' | tr '%' '\\' 2>/dev/null`
  local escaped_label=`echo $label | sed 's/\//%\//g' | tr '%' '\\' 2>/dev/null`
  fs_tab_content=`perl -ne "s/($escaped_part|UUID=$uuid|LABEL=$escaped_label)[\s](?!\/boot)(.*)$/$name \$2/; print;" /etc/fstab`
  echo "$fs_tab_content" >/etc/fstab
  echo $3
  echo $4
}

replace_home_tmp () {
  local dir=$1
  local name=$2
  local count=`cat /etc/fstab | grep -E "^[^[:space:]]*.\/$dir[[:space:]].*$"`
  if [ "$count" != "0" ]; then
    content=`sed -r "s/^[^[:space:]]*(.\/$dir[:space:].*)$/\/dev\/lvm_volume_group\/$name \1/" /etc/fstab`
    echo "$content" >/etc/fstab
  else
    echo "/dev/lvm_volume_group/$name /$dir ext4 defaults 0 0"
  fi
}

if [ "$(id -u)" != "0" ]; then
  echo "Must be run as root"
  exit 1
fi
pvcreate /dev/sdb
vgcreate lvm_volume_group /dev/sdb
old_partitions=`fdisk -l /dev/sda | grep '^/dev' | cut -d' ' -f1`
mkdir /mnt/src
mkdir /mnt/dst
prev_name="2"
for part in $old_partitions
do
  name="l`echo $part | sed -E "s/^\/dev\/(.*)/\1/"`"
  size=`blockdev --getsize64 $part`
  size=`echo "$size + $size/2" | bc`
  fs=`blkid $part | sed -E "s/.*TYPE=\"([^\"]*).*/\1/"`
  create_lv $name $size"B" $fs
  mount -t $fs $part /mnt/src
  mount -t $fs /dev/lvm_volume_group/$name /mnt/dst
  cp -a /mnt/src/* /mnt/dst
  umount /mnt/src
  umount /mnt/dst
  replace_mnt  $part "\/dev\/lvm_volume_group\/$name" "$prev_name" "$name"
  prev_name=$name
done
create_lv "ltmp" "1G" "ext4"
mount -t ext4 /dev/lvm_volume_group/ltmp /mnt/dst
cp -a /tmp/* /mnt/dst
umount /mnt/dst
replace_home_tmp "tmp" "ltmp"
home_size=`du -sb /home/ | sed -E "s/^([^[:space:]]*).*$/\1/"`
home_size=`echo "$home_size + $home_size/2" | bc`
create_lv "lhome" $home_size "ext4"
mount -t ext4 /dev/lvm_volume_group/lhome /mnt/dst
cp -a /home/* /mnt/dst
umount /mnt/dst
replace_home_tmp "home" "lhome"
rmdir /mnt/src
rmdir /mnt/dst
